package com.tea.modules.util;

import cn.hutool.extra.pinyin.PinyinEngine;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Objects;

/**
 * com.tea.modules.util <br>
 * 多音字问题，客户名字带长字，系统简称为z，应该为c
 * @author jaymin
 * @since 2022/2/22
 */
public class SpecialPinyin4jEngineOfFixBug implements PinyinEngine {
    HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

    @Override
    public String getPinyin(char c) {
        return null;
    }

    @Override
    public String getPinyin(String chineseString, String separator) {
        StringBuilder pinyin = new StringBuilder();
        String temp = "";
        String[] resolvePinyinArray;
        for (int i = 0; i < chineseString.length(); i++) {
            char c = chineseString.charAt(i);
            if ((int) c <= 128) {
                pinyin.append(c);
            } else {
                try {
                    resolvePinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    throw new RuntimeException("解析拼音出错:" + e);
                }
                if (resolvePinyinArray == null) {
                    pinyin.append(c);
                } else {
                    temp = resolvePinyinArray[0];
                    if (Objects.equals("zhang3", temp)) {
                        temp = "C";
                    } else {
                        temp = resolvePinyinArray[0].toUpperCase().charAt(0) + temp.substring(1);
                        if (temp.length() >= 1) {
                            temp = temp.substring(0, 1);
                        }
                    }
                    pinyin.append(temp).append(i == chineseString.length() - 1 ? "" : separator);
                }
            }
        }
        return pinyin.toString().trim();
    }
}
